/*
 *所有关于table_wgjy类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*table_wgjyService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using ATkg.BizAppProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;
using Newtonsoft.Json.Linq;
using ClosedXML.Excel;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.IRepositories;
using DGZImp.Core.EFDbContext;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using DGZImp.Core.Exceptions;
using Newtonsoft.Json.Linq;
using NetTaste;
using System.Diagnostics;
using System.Text.Json;
using System;
using System.Text.Json;
using SqlSugar.DistributedSystem.Snowflake;
using Newtonsoft.Json;
using DocumentFormat.OpenXml.Bibliography;
using System.IdentityModel.Tokens.Jwt;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Office2010.ExcelAc;
using System.Globalization;
using DGZImp.Core.DbSqlSugar;
using DocumentFormat.OpenXml.Spreadsheet;
using static ATkg.BizAppProject.Controllers.table_wgjyController;
using DocumentFormat.OpenXml.InkML;
using Org.BouncyCastle.Utilities.Collections;

namespace ATkg.BizAppProject.Services
{

    public partial class table_wgjyService : Itable_wgjyService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Itable_wgjyRepository _repository;//访问数据库

        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        public IConfiguration _config;
        public HttpClient client = null;
        public static IHttpClientFactory _httpClientFactory { get; set; }

        public AmesSyncService ames = AutofacContainerModule.GetService<AmesSyncService>();
        public ILogger<AmesSyncService> logger { get; set; }


        // 定义与 JSON 结构匹配的模型类
        // 定义对应的数据模型类
        public class SteelGradeData
        {
            public List<object> steelgrade_id { get; set; }
            public double batch_todo_qty { get; set; }
            public int id { get; set; }
            public List<object> schedule_blank_id { get; set; }
        }

        public class MyItem
        {
            public List<object> steelgrade_id { get; set; } // 假设 steelgrade_id 是 object 列表
            public double batch_todo_qty { get; set; }
            public int id { get; set; }
            public List<object> schedule_blank_id { get; set; }
        }

        [ActivatorUtilitiesConstructor]
        public table_wgjyService(
            Itable_wgjyRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);            

        }


        public async Task<object> SyncProductionTask_wgjy(string taskNo = "")
        {
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";
            var isSingle = taskNo.IsValuable();
            Console.WriteLine(taskNo);
            var typeArray = new[] { "final" };

            var qDomain = new List<object> {

                new List<object> { "production_type", "=", "final" }
            };

            if (isSingle)
            {
                Console.WriteLine("DDDDDD");
                qDomain.Add("|");
                qDomain.Add(new List<object> { "name", "ilike", taskNo });
                qDomain.Add(new List<object> { "origin", "ilike", taskNo });
                //Console.WriteLine(qDomain.ToArrayString);
            }
            //else
            //{
            //    qDomain.Add(new List<object> { "state", "=", "in_production" });
            //}

            var qFields = new List<string> {
                "id",
                "raw_lot_id",
                "product_id",
                "prodcut_spec",
                "grade",
                "raw_resume_stock_qty",
                "partner_id"
            };
            var qPage = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };

            var resp = await ames.Get_stoke_("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var Product = "";
            //Console.WriteLine(r);
            Console.WriteLine("FFF");
            object id_ = res[0]["id"];
            object partner = res[0]["partner_id"][1];
            object prodcut_spec = res[0]["prodcut_spec"];
            string raw_lot_id_ = (string)res[0]["raw_lot_id"][1];
            object grade = res[0]["grade"][1];
            object raw_resume_stock_qty = res[0]["raw_resume_stock_qty"];
            string raw_lot_id = "";
            if (raw_lot_id_.Contains("-C"))
            {
                Console.WriteLine("包含有");
                string aw_lot_id__ = raw_lot_id_.Split("-C")[0];
                raw_lot_id = aw_lot_id__;
            }
            else
            {
                Console.WriteLine("meiyou");
                raw_lot_id = raw_lot_id_;
            }
            Console.WriteLine(raw_lot_id);
            //var typeArray_1 = new[] { "final" };

            var qDomain_read = new List<object> {

                id_
            };

            var qFields_read = new List<string> {
                "id",
                "top_id",
                "lot_ids"
            };
            var qPage_read = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_read = await ames.Get_stoke_read("mrp.production", qDomain_read, qFields_read, qPage_read);
            var res_read = (JArray)resp_read["result"];
            string product_ = (string)res_read[0]["top_id"][1];
            object lot_ids = res_read[0]["lot_ids"][0];
            string product = "";
            if (raw_lot_id_.Contains(" "))
            {
                Console.WriteLine("包含有");
                product = product_.Replace(" ", "");
            }
            else
            {
                Console.WriteLine("meiyou");
                product = product_;
            }
            //var typeArray = new[] { "final" };

            var qDomain_3 = new List<object> {

                new List<object> { "lot_id", "ilike", raw_lot_id }
            };
            //else
            //{
            //    qDomain.Add(new List<object> { "state", "=", "in_production" });
            //}

            var qFields_3 = new List<string> {
                "id"
            };
            var qPage_3 = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_3 = await ames.Get_stoke_("atm.qc.inspect.visual", qDomain_3, qFields_3, qPage_3);
            Console.WriteLine(resp_3);
            var res_read_3 = (JArray)resp_3["result"];
            object id_4 = res_read_3[0]["id"];
            var qDomain_read_4 = new List<object> {
                id_4
            };

            var qFields_read_4 = new List<string> {
                "plating_qualified_fianl_qty",
                "sampling_reliability_qty"
            };
            var qPage_read_4 = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_read_4 = await ames.Get_stoke_read("atm.qc.inspect.visual", qDomain_read_4, qFields_read_4, qPage_read_4);
            var res_read_4 = (JArray)resp_read_4["result"];
            //object id_4 = res_read_4[0]["id"];
            object sampling_reliability_qty = res_read_4[0]["sampling_reliability_qty"];
            object plating_qualified_fianl_qty = res_read_4[0]["plating_qualified_fianl_qty"];

            var qDomain_read_5 = new List<object> {
                lot_ids
            };

            var qFields_read_5 = new List<string> {
                "id",
                "piece_weight"
            };
            var qPage_read_5 = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_read_5 = await ames.Get_stoke_read("stock.production.lot", qDomain_read_5, qFields_read_5, qPage_read_5);
            var res_read_5 = (JArray)resp_read_5["result"];
            object piece_weight = res_read_5[0]["piece_weight"];

            var qDomain_6 = new List<object> {

                new List<object> { "name", "ilike", product }
            };
            //else
            //{
            //    qDomain.Add(new List<object> { "state", "=", "in_production" });
            //}

            var qFields_6 = new List<string> {
                "id"
            };
            var qPage_6 = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_6 = await ames.Get_stoke_("atm.plm.top", qDomain_6, qFields_6, qPage_6);
            Console.WriteLine(resp_6);
            var res_read_6 = (JArray)resp_6["result"];
            object id_6 = res_read_6[0]["id"];

            var qDomain_read_7 = new List<object> {
                id_6
            };

            var qFields_read_7 = new List<string> {
                "id",
                "steelgrade_id"
            };
            var qPage_read_7 = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_read_7 = await ames.Get_stoke_read("atm.plm.top", qDomain_read_7, qFields_read_7, qPage_read_7);
            var res_read_7 = (JArray)resp_read_7["result"];
            object steelgrade_id = res_read_7[0]["steelgrade_id"];
            string recycle_grade = "";

            try
            {
                object steelgrade_id_ = res_read_7[0]["steelgrade_id"][0];
                var qDomain_read_8 = new List<object> {
                steelgrade_id_
                };

                var qFields_read_8 = new List<string> {
                "id",
                "recycle_grade"
                };
                var qPage_read_8 = new
                {
                    limit = 10000,
                    offset = 0,
                    order = "name desc",
                };
                var resp_read_8 = await ames.Get_stoke_read("atm.product.steelgrade", qDomain_read_8, qFields_read_8, qPage_read_8);
                var res_read_8 = (JArray)resp_read_8["result"];
                recycle_grade = (string)res_read_8[0]["recycle_grade"];
            }
            catch
            {
                recycle_grade = "";
            }
            var r = new List<object>();
            r.Add(new
            {
                product = product,
                partner = partner,
                prodcut_spec = prodcut_spec,
                raw_lot_id = raw_lot_id,
                raw_resume_stock_qty = raw_resume_stock_qty,
                piece_weight = piece_weight,
                recycle_grade = recycle_grade,
                grade = grade,
                plating_qualified_fianl_qty = plating_qualified_fianl_qty,
                sampling_reliability_qty = sampling_reliability_qty,
            });
            //for (var i = 0; i < res.Count; i++)
            //{
            //    var x = (JObject)res[i];
            //    Console.WriteLine(x);
            //    Console.WriteLine(i);
            //r.Add(new
            //{               

            //});
            //    DianduNo = x["name"].ToString(),
            //    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
            //    Grade = x["grade"] is JArray ? JArray.FromObject(x["grade"])[1].ToString() : "",
            //    Spec = x["prodcut_spec"].ToString(),
            //    IncomeQty = (int)x["produced_qty"],
            //});
            //}
            return new
            {
                rows = r,
                total = res.Count
            };
        }

        public class SteelName {
            public string steelgrade_id;
            public int batch_todo_qty;
            public int total_weight;


        }

        public class FinalJSData
        {
            public List dimensions;
            public List source;
        }


        public async Task<object> Sync_cailiao_plan_data()
        {
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";

            var typeArray = new[] { "final" };

            var qDomain = new List<object> {
                new List<object> { "workshop_type","=","material" },
                new List<object> { "state","!=","draft" },
                new List<object> { "schedule_state","not in",new List<object> { "draft", "cancel" } },
                new List<object> { "state","in", new List<object> { "ready", "confirmed", "in_production" } },
                new List<object> { "date_start",">=","2025-01-01" }
            };
            var qFields = new List<string> {
                "id", "steelgrade_id", "batch_todo_qty", "schedule_blank_id"
            };
            var qPage = new
            {  };
            var resp = await ames.Get_info_gzd("mps.schedule.line", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return 0;
            }
            List<SteelName> list_out_o = new List<SteelName>();
            for (int i = 0; i < res.Count; i++)
            {
                if ((int)res[i]["batch_todo_qty"] > 0)
                {
                    list_out_o.Add(new SteelName
                    {
                        steelgrade_id = res[i]["steelgrade_id"] is JArray ? (string)((JArray)res[i]["steelgrade_id"])[1] : "",
                        batch_todo_qty = (int)res[i]["batch_todo_qty"]
                    });
                }
            }
            list_out_o = list_out_o.GroupBy(i => i.steelgrade_id).Select(i =>    //list_out_o按照steelgrade_id进行分组，将
            {
                return new SteelName
                {
                    steelgrade_id = i.Key,
                    batch_todo_qty = i.Sum(x => x.batch_todo_qty),
                    total_weight = i.Sum(x => x.batch_todo_qty) * 350
                };
            }).ToList();
            var result_data = new List<cailiao_plan_data>();
            for (int i=0; i < list_out_o.Count; i++)
            {                
                if (list_out_o[i].steelgrade_id == "")
                {
                    continue;
                }
                else
                {
                    var steelgrade_name = list_out_o[i].steelgrade_id;                    
                    var qDomain_per = new List<object> {
                        new List<object> { "name","=",steelgrade_name }
                    };
                    var qFields_per = new List<string> {
                        "id", "material_ids"
                    };
                    var qPage_per = new
                    { };
                    var resp_per = await ames.Get_info_gzd("atm.product.steelgrade", qDomain_per, qFields_per, qPage_per);
                    var material_ids_ed = (JArray)resp_per["result"];
                    JArray mest = (JArray)material_ids_ed[0]["material_ids"];
                    List<int> info_list = new List<int>();
                    var qDomain_read = new List<object> { };
                    for (int jj = 0; jj < mest.Count; jj++)
                    {
                        qDomain_read.Add((int)material_ids_ed[0]["material_ids"][jj]);
                    }

                    var qFields_read = new List<string> {
                        "id",
                        "percent",
                        "product_product_id"
                    };
                    var qPage_read = new
                    {
                        limit = 10000,
                        offset = 0,
                        order = "name desc",
                    };
                    var resp_read = await ames.Get_stoke_read("atm.product.steelgrade.material", qDomain_read, qFields_read, qPage_read);
                    var material_zhanbi = (JArray)resp_read["result"];
                    int per_zhanbi = material_zhanbi.Count;
                    List<string> five_zhanbi = new List<string>();
                    for (int one_ZB = 0; one_ZB < per_zhanbi; one_ZB++)
                    {
                        int zhanbi_percent = (int)material_zhanbi[one_ZB]["percent"];
                        float a_data = (float)(zhanbi_percent * list_out_o[i].total_weight / 100);
                        string name = material_zhanbi[one_ZB]["product_product_id"] is JArray ?
                            (string)((JArray)material_zhanbi[one_ZB]["product_product_id"])[1] : "";
                        five_zhanbi.Add(a_data.ToString("0.00", CultureInfo.InvariantCulture) +"(" +name+")");
                        if(one_ZB+1 == per_zhanbi)
                        {
                            int count_over = 5 - per_zhanbi;
                            for(int over_zhanbi = 0;over_zhanbi< count_over; over_zhanbi++)
                            {
                                five_zhanbi.Add("");
                            }                            
                        }                            
                     }                    

                    result_data.Add(new cailiao_plan_data
                    {
                        SteelgradeName = steelgrade_name,
                        TotalWeightPer = list_out_o[i].total_weight,
                        BatchAllQty = list_out_o[i].batch_todo_qty,
                        Material1 = five_zhanbi[0],
                        Material2 = five_zhanbi[1],
                        Material3 = five_zhanbi[2],
                        Material4 = five_zhanbi[3],
                        Material5 = five_zhanbi[4],

                    });      
                }
            }

            await Db.DoDeleteAsync<cailiao_plan_data>(x => x.CreateId >= 0,true);
            await Db.DoInsertAsync<cailiao_plan_data>(result_data);
            
            var title = new List<DimensionData>();
            string[] title_ = { "钢号", "需求量", "钢种1", "钢种2", "钢种3", "钢种4", "钢种5" };
            title.Add(new DimensionData
            {
                title = ""
            });
            var final_data_return = new List<FinalJSData>();
            final_data_return.Add(new FinalJSData
            {
                //dimensions = [{ "title":"产品名称","key":"productName", "align":"center" },
                //{ "title":"产品销量（万）", "key":"totalSum", "align":"center" },
                //{ "title":"销售额（万）", "key":"totalAmount", "align":"center" },
                //{ "title":"销售额（万）", "key":"totalAmount", "align":"center" },
                //{ "title":"销售额（万）", "key":"totalAmount", "align":"center" }];
            });

            return list_out_o;
        }

        public class DimensionData
        {
            public string title;
            public string key;
            public string align;
        }


        public async Task<object> SyncProductionTask_wgjy_pg(string taskNo = "", JObject mes_data_final = null)
        {
            Console.WriteLine("进来了！！！");
            Console.WriteLine(mes_data_final);
            Console.WriteLine(mes_data_final["defect_plating_disability_final_qty"]);
            Console.WriteLine(mes_data_final["inspection_time"]);
            //ames.userName = "duyang@atmcn.com";
            //ames.password = "Du123456*";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";
            ames.userName = "oqc-1@atmcn.com";
            ames.password = "oqc12345";
            var isSingle = taskNo.IsValuable();
            Console.WriteLine(taskNo);
            var typeArray = new[] { "final" };

            var qDomain = new List<object> {
            };

            if (isSingle)
            {
                Console.WriteLine("DDDDDD");
                qDomain.Add(new List<object> { "lot_id", "ilike", taskNo });
            }
            var qFields = new List<string> {
                "id"
            };
            var qPage = new
            {
                limit = 1,
                offset = 0,
                order = "name desc",
            };

            var resp = await ames.Get_info_gzd("atm.qc.inspect.visual", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            Console.WriteLine("FFF");
            int id_ = (int)res[0]["id"];            
            //JObject mes_data_local = mes_data_final;
            var resp_name_w = await ames.up_to_messys_wgjy("atm.qc.inspect.visual", id_, mes_data_final);
            Console.WriteLine(resp_name_w);
            var resp_name_d = await ames.done_to_messys("atm.qc.inspect.visual", id_);
            Console.WriteLine(resp_name_d);
            return new
            {
                rows = resp_name_d,
                total = resp_name_d.Count
            };
        }

        public async Task<object> gzd_search_task(string taskNo = "")
        {
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";
            Console.WriteLine("duyangde ");
            var isSingle = taskNo.IsValuable();
            Console.WriteLine(taskNo);
            var typeArray = new[] { "final" };

            var qDomain = new List<object> {

                new List<object> { "source", "=", "original" }
            };

            if (isSingle)
            {
                Console.WriteLine("DDDDDD");
                //qDomain.Add("|");
                qDomain.Add(new List<object> { "lot_id", "ilike", taskNo });
                //qDomain.Add(new List<object> { "origin", "ilike", taskNo });
                //Console.WriteLine(qDomain.ToArrayString);
            }
            //else
            //{
            //    qDomain.Add(new List<object> { "state", "=", "in_production" });
            //}

            var qFields = new List<string> {
                "id",
                "insp_quality_state",
                "state",
                "judgement",
                "value_max",
                "value_min",
                "result_id"
            };
            var qPage = new
            {
                limit = 1,
                offset = 0,
                order = "name desc",
            };

            var resp = await ames.Get_info_gzd("atm.qc.inspect.glossiness", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                Console.WriteLine("是空的！！");
                return 0;
            }
            Console.WriteLine(res);
            return new
            {
                rows = res,
                total = res.Count
            };
        }

        public async Task<object> gzd_upmes_excel_task(string taskNo = "", string order_id = "", float[] gzd_data = null, int[] mes_old_data_id = null)
        {
            Console.WriteLine("进来了！！！");
            Console.WriteLine(gzd_data[0]);
            Console.WriteLine(mes_old_data_id);
            Console.WriteLine("test mes");
            ames.userName = "chicun@atmcn.com";
            ames.password = "cc123456789";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";
            Console.WriteLine("duyangde ");
            var isSingle = taskNo.IsValuable();
            Console.WriteLine(taskNo);
            var typeArray = new[] { "final" };

            var id_order = int.Parse(order_id);
            var qDomain_name = new List<object> {
                //qDomain_name.Add("|");
                //new List<object> { "source", "=", "original" }
            };

            if (isSingle)
            {
                Console.WriteLine("DDDDDD");
                qDomain_name.Add("|");
                qDomain_name.Add("|");
                qDomain_name.Add(new List<object> { "display_name", "ilike", taskNo });
                qDomain_name.Add(new List<object> { "ref", "=", taskNo });
                qDomain_name.Add(new List<object> { "email", "ilike", taskNo });
                qDomain_name.Add(new List<object> { "category_id", "child_of", 14 });
            }


            var qFields_name = new List<string> {
                "id",
                "display_name"
            };
            var qPage_name = new
            {
                limit = 1,
                offset = 0,
                order = "name desc",
            };
            var resp_name = await ames.Get_name_id("res.partner", qDomain_name, qFields_name, qPage_name);
            var aa = resp_name["result"];
            //Array BB = (Array)aa;
            JArray jArray = (JArray)resp_name["result"];
            object[] array = jArray.ToObject<object[]>();
            var name_id = 0;
            if (array.Length == 0)
            {
                name_id = 0;
            }
            else
            {
                name_id = (int)resp_name["result"][0]["id"];
            }

            Console.WriteLine(name_id);
            Console.WriteLine("name_id");
            var n_all_data = gzd_data.Length;
            var n_row_ = n_all_data / 3;
            var mod_n = n_all_data % 3;
            var n_rows = 0;
            if (mod_n == 0)
            {
                n_rows = n_row_;
            }
            else
            {
                n_rows = n_row_ + 1;
            }
            List<object> result_data_in_list = new List<object> { };
            if (n_rows == mes_old_data_id.Length)
            {
                for (int i = 0; i < n_rows; i++)
                {
                    if (n_rows == i + 1)
                    {
                        object[] single_data = null;
                        if (mod_n == 1)
                        {
                            single_data = new object[]
                            {
                                1,
                                mes_old_data_id[i],
                                new Dictionary<string, object> { { "value_1", gzd_data[i * 3] } }
                            };
                        }
                        else if (mod_n == 2)
                        {
                            single_data = new object[]
                            {
                                1,
                                mes_old_data_id[i],
                                new Dictionary<string, object> { { "value_1", gzd_data[i * 3] } , { "value_2", gzd_data[i * 3 + 1] } }
                            };
                        }
                        else
                        {
                            single_data = new object[]
                            {
                                1,
                                mes_old_data_id[i],
                                new Dictionary<string, object> { { "value_1", gzd_data[i * 3] } , { "value_2", gzd_data[i * 3 + 1] }, { "value_3", gzd_data[i * 3 + 2] } }
                            };
                        }
                        result_data_in_list.Add(single_data);
                    }
                    else
                    {
                        object[] single_data = new object[]
                            {
                                1,
                                mes_old_data_id[i],
                                new Dictionary<string, object> { { "value_1", gzd_data[i * 3] } , { "value_2", gzd_data[i * 3 + 1] }, { "value_3", gzd_data[i * 3 + 2] } }
                            };
                        result_data_in_list.Add(single_data);
                    }
                }
            }
            else if (n_rows < mes_old_data_id.Length)
            {
                for (int i = 0; i < mes_old_data_id.Length; i++)
                {
                    List<object> single_data = new List<object> { };
                    if (i + 1 == n_rows)
                    {
                        if (mod_n == 1)
                        {
                            single_data.Add(1);
                            single_data.Add(mes_old_data_id[i]);
                            single_data.Add(new Dictionary<string, object> { { "value_1", gzd_data[i * 3] } });
                        }
                        else if (mod_n == 2)
                        {
                            single_data.Add(1);
                            single_data.Add(mes_old_data_id[i]);
                            single_data.Add(new Dictionary<string, object> { { "value_1", gzd_data[i * 3] }, { "value_2", gzd_data[i * 3 + 1] } });
                        }
                        else
                        {
                            single_data.Add(1);
                            single_data.Add(mes_old_data_id[i]);
                            single_data.Add(new Dictionary<string, object> { { "value_1", gzd_data[i * 3] },
                                { "value_2", gzd_data[i * 3 + 1] }, { "value_3", gzd_data[i * 3 + 2] } });
                        }
                        result_data_in_list.Add(single_data);
                    }
                    else if (i + 1 > n_rows)
                    {
                        single_data.Add(2);
                        single_data.Add(mes_old_data_id[i]);
                        single_data.Add(false);
                        result_data_in_list.Add(single_data);
                    }
                    else
                    {
                        single_data.Add(1);
                        single_data.Add(mes_old_data_id[i]);
                        single_data.Add(new Dictionary<string, object> { { "value_1", gzd_data[i * 3] }, { "value_2", gzd_data[i * 3 + 1] }, { "value_3", gzd_data[i * 3 + 2] } });
                        result_data_in_list.Add(single_data);
                    }

                }

            }
            else
            {
                for (int i = 0; i < n_rows; i++) {
                    List<object> single_data = new List<object> { };
                    if (i + 1 == n_rows)
                    {
                        if (mod_n == 1)
                        {
                            single_data.Add(0);
                            single_data.Add(false);
                            single_data.Add(new Dictionary<string, object> { { "value_1", gzd_data[i * 3] },
                                { "value_2", 0}, { "value_3", 0 }, { "value_4", 0 }, { "value_5", 0 } });
                        }
                        else if (mod_n == 2) {
                            single_data.Add(0);
                            single_data.Add(false);
                            single_data.Add(new Dictionary<string, object> { { "value_1", gzd_data[i * 3] },
                                { "value_2", gzd_data[i * 3 + 1]}, { "value_3", 0 }, { "value_4", 0 }, { "value_5", 0 } });
                        }
                        else
                        {
                            single_data.Add(0);
                            single_data.Add(false);
                            single_data.Add(new Dictionary<string, object> { { "value_1", gzd_data[i * 3] },
                                { "value_2", gzd_data[i * 3 + 1]}, { "value_3", gzd_data[i * 3 + 2] }, { "value_4", 0 }, { "value_5", 0 } });
                        }
                        result_data_in_list.Add(single_data);
                    }
                    else
                    {
                        if (i + 1 == mes_old_data_id.Length)
                        {
                            single_data.Add(1);
                            single_data.Add(false);
                            single_data.Add(new Dictionary<string, object> { { "value_1", gzd_data[i * 3] },
                                { "value_2", gzd_data[i * 3 + 1]}, { "value_3", gzd_data[i * 3 + 2] }});
                        } else
                        {
                            single_data.Add(0);
                            single_data.Add(false);
                            single_data.Add(new Dictionary<string, object> { { "value_1", gzd_data[i * 3] },
                                { "value_2", gzd_data[i * 3 + 1]}, { "value_3", gzd_data[i * 3 + 2] }, { "value_4", 0 }, { "value_5", 0 } });
                        }
                        result_data_in_list.Add(single_data);
                    }
                }
            }


            Console.WriteLine("数据格式看看！！！");
            Console.WriteLine(result_data_in_list);
            Console.WriteLine(result_data_in_list);

            Dictionary<string, object> result_data_final = new() {  };
            DateTime currentTime = DateTime.Now;
            // 以 yyyy-MM-dd 格式显示
            string formattedDate = currentTime.ToString("yyyy-MM-dd");
            if (name_id == 0)
            {
                result_data_final = new() { { "result_id", result_data_in_list }, { "inspection_time", formattedDate } };
            }
            else
            {
                result_data_final = new() { { "result_id", result_data_in_list }, { "inspector", name_id } , { "inspection_time", formattedDate } };
            }
            Console.WriteLine(result_data_final);

            var qDomain_name_w = new List<object>
            {
                //qDomain_name.Add("|");
                //new List<object> { "source", "=", "original" }
            };
            if (isSingle)
            {
                Console.WriteLine("DDDDDD");
                qDomain_name_w.Add(new List<object> { id_order });
                qDomain_name_w.Add(result_data_final);
            }            
            var resp_name_w = await ames.up_to_messys("atm.qc.inspect.glossiness", id_order,result_data_final);
            Console.WriteLine(resp_name_w);
            var qDomain_name_d = new List<object>
            {
                //qDomain_name.Add("|");
                //new List<object> { "source", "=", "original" }
            };
            if (isSingle)
            {
                Console.WriteLine("DDDDDD");
                qDomain_name_d.Add(new List<object> { id_order });
            }
            var resp_name_d = await ames.done_to_messys("atm.qc.inspect.glossiness",id_order);
            Console.WriteLine(resp_name_d);
            return new
            {
                rows = resp_name_d,
                total = resp_name_d.Count
            };
        }


        public async Task<object> save_excel_task(string name_order = "", string lot_name = "", float[] gzd_data = null,string formattedTime="", 
            string path_file_mode = "",string formattedTime_ymd = "",string test_modle = "")
        {

            try
            {
                // 创建一个新的 Excel 工作簿
                using (var workbook = new XLWorkbook())
                {
                    // 添加一个工作表
                    var worksheet = workbook.Worksheets.Add("Sheet1");
                    for(int i = 0; i < gzd_data.Length; i++)
                    {
                        // 在工作表中添加一些示例数据
                        worksheet.Cell(i+1, 1).Value = gzd_data[i];
                    }                   

                    string fileNameParam = test_modle + " " + lot_name + " " + formattedTime + " " + name_order;

                    // 动态组合文件名
                    string fileName = $"{fileNameParam}.xlsx";
                    string data_today = formattedTime_ymd;

                    // 定义保存文件的基础路径
                    string basePath = "";
                    if (path_file_mode == "@")
                    {
                        basePath = string.Format(@"\\10.7.1.22\品管部\品管部存储文件\多功能测试\2025\含@文件\{0}", data_today);
                    }
                    else if (path_file_mode == "未报工")
                    {
                        basePath = @"\\10.7.1.22\品管部\品管部存储文件\多功能测试\2025\数据存储";
                    }
                    else if (path_file_mode == "已报工")
                    {
                        basePath = string.Format(@"\\10.7.1.22\品管部\品管部存储文件\多功能测试\2025\已报工\{0}", data_today);
                    }

                    // 确保目标文件夹存在
                    Directory.CreateDirectory(basePath);

                    // 完整的文件保存路径
                    string fullPath = Path.Combine(basePath, fileName);


                    // 保存 Excel 文件
                    await Task.Run(() => workbook.SaveAs(fullPath));

                    return new { Success = true, Message = "Excel 文件保存成功", FilePath = fullPath };
                }
            }
            catch (Exception ex)
            {
                return new { Success = false, Message = $"保存 Excel 文件时出错: {ex.Message}" };
            }
            
        }


        public class QueryCondition
        {
            public string name { get; set; }

            public List<object[]> args { get; set; }

            public string @operator { get; set; }

            public Context context { get; set; }
        }
        public class Context
        {
            public string lang { get; set; } = "zh_CN"; // 默认值，可直接赋值
            public string tz { get; set; } = "Asia/Shanghai";
            public int uid { get; set; } = 259;
            public bool show_name { get; set; } = true; // 对应JSON的true
        }
        public async Task<object> up_to_mes_()
        {
            
            Console.WriteLine("质量检测！！！");
            ames.userName = "chicun@atmcn.com";
            ames.password = "cc123456789";
            ames.url = "http://10.7.1.3/jsonrpc";
            ames.db = "atm";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";
            string[] jiagongc = { "成检一工段", "成检二工段", "成检三工段", "成检四工段", "成检五工段" };

            var result = Db.Queryable<test_pg_nk>()  //                      
                .Where(it => it.isUploaded == "未上传")    
                .Select(m => new
                    {
                        m.TestName,
                        m.Lot,
                        m.TestData,
                        m.TestPerson,
                        m.TestTime,
                        m.isUploaded
                    })               // 选择 update_data 字段
                    .ToList();                               // 执行查询并返回列表
            for(int i = 0; i < result.Count; i++)
            {
                Console.WriteLine("LLLL");
                Console.WriteLine(result[i]);
                string lot_ = result[i].Lot;
                string modle_ = result[i].TestName;
                string testresult = result[i].TestData;
                string testperson = result[i].TestPerson;
                string testtime = result[i].TestTime;
                var qDomain = new List<object> {
                    new List<object> { "source", "=","original" },
                    "|",
                    new List<object> { "state", "=", "draft"},
                    new List<object> { "state", "=", "done"},
                    new List<object> { "lot_id", "ilike", lot_},
                };
                Console.WriteLine(qDomain);
                var qFields = new List<string> {
                    "id","state","partner_id"
                };
                var qPage_per = new
                { };
                var resp = await ames.Get_info_gzd(modle_, qDomain, qFields, qPage_per);
                if (resp.ContainsKey("error"))
                {
                    var message = $"【拉取单据】{resp["error"].ToString()}";
                    throw new AppException(message);
                }
                var res = (JArray)resp["result"];
                if (res.Count > 0)
                {
                    Console.WriteLine(lot_);
                    Console.WriteLine(res);

                    var condition = new QueryCondition
                    {
                        name = testperson,
                        args = new List<object[]>
                        {
                            new object[] { "category_id", "child_of", 14 } // 内层混合类型数组
                        },
                        @operator = "ilike",
                        context = new Context() // 嵌套对象（已设默认值，可直接new）
                    };
                    var resp_name = await ames.name_research("res.partner", condition);
                    Console.WriteLine(resp_name);
                    var res_name = (JArray)resp_name["result"];
                    // 构建返回对象（Dictionary 方式）
                    var inputData = new Dictionary<string, object>
                        {
                            { "judgement", testresult },
                            { "inspection_time", testtime }
                        };
                    if (res_name.Count > 0)
                    {
                        int name_id = (int)res_name[0][0];
                        inputData.Add("inspector", name_id);
                    }
                    for(int j=0;j< res.Count; j++)
                    {
                        string state_ = res[j]["state"].ToString();
                        if (state_ == "done")
                        {
                            int rowsAffected = Db.Updateable<test_pg_nk>()
                            .SetColumns(it => new test_pg_nk
                            {
                                isUploaded = "已上传",
                            })
                            .Where(it => it.Lot == lot_) // 精确条件
                            .ExecuteCommand();
                        }
                        else
                        {
                            string jiagongchang_ = res[j]["partner_id"][1].ToString();
                            bool exists = Array.Exists(jiagongc, element => element == jiagongchang_);
                            if (!exists)
                            {
                                int id_ = (int)res[j]["id"];
                                var resp_name_w = await ames.up_to_messys(modle_, id_, inputData);
                                var resp_name_d = await ames.done_to_messys(modle_, id_);
                                int rowsAffected = Db.Updateable<test_pg_nk>()
                                .SetColumns(it => new test_pg_nk
                                {
                                    isUploaded = "已上传",
                                })
                                .Where(it => it.Lot == lot_) // 精确条件
                                .ExecuteCommand();
                            }                            
                        }
                    }                    
                }
            }
            return 11;
        }
    }
}
